<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-button type="primary" @click="openUploadFileDialog = true"
        >点击上传文件<i class="el-icon-upload el-icon--right"></i>
      </el-button>
      <el-form-item label="文件名" prop="docName">
        <el-input
          v-model="queryParams.docName"
          placeholder="请输入文件名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >刷新</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="sdocList"
      @selection-change="handleSelectionChange"
    >
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="文件名称" width="250" prop="docName" />
      <el-table-column label="文件类型" width="150" align="center" prop="docType" />
      <el-table-column label="文件存储地址" width="300" align="center" prop="docUrl" />
      <el-table-column label="库表代码" width="250" align="center" prop="docTableCode" />
      <!--      <el-table-column label="文件描述" align="center" prop="docDescription"/>-->
      <el-table-column label="是否创建表" width="100" align="center">
        <template slot-scope="scope">
          <el-switch
            disabled
            v-model="scope.row.isExistTable"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="是否数据入库" width="100" align="center">
        <template slot-scope="scope">
          <el-switch
            align="center"
            disabled
            v-model="scope.row.isExistData"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <div>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-mouse"
              @click="lookField(scope.row)"
              >字段编辑
            </el-button>
          </div>
          <div v-if="scope.row.isExistTable == 0">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="handleCreateTable(scope.row)"
              >生成库表
            </el-button>
          </div>
          <div v-if="scope.row.isExistData == 0">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-s-promotion"
              @click="handleDataSave(scope.row)"
              >数据入库
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="totalCount > 0"
      :page-sizes="[5, 10, 20]"
      :page-size="5"
      :total="totalCount"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog
      title="标准文件上传"
      destroy-on-close
      v-dialogDrag
      :visible.sync="openUploadFileDialog"
      width="60%"
      center
    >
      <up-load class="uploadSlot"></up-load>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="openUploadFileDialog = false">确 定</el-button>
        <el-button @click="openUploadFileDialog = false">取 消</el-button>
      </span>
      <!--      <el-upload-->
      <!--        ref="upload"-->
      <!--        :limit=10-->
      <!--        drag-->
      <!--        accept=".xlsx,.xls,.txt,.csv"-->
      <!--        :action="upload.url"-->
      <!--        :name="upload.filePath"-->
      <!--        :headers="upload.headers"-->
      <!--        :multiple=false-->
      <!--        :auto-upload="false"-->
      <!--        :on-success="uploadSuccess">-->
      <!--        <i class="el-icon-upload"></i>-->
      <!--        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>-->
      <!--        <div class="el-upload__tip" style="color:red" slot="tip">提示:只能上传.xlsx,.xls,.csv,.txt文件</div>-->
      <!--      </el-upload>-->
      <!--      <div slot="footer" class="dialog-footer">-->
      <!--        <el-button type="primary" @click="submitFileForm">上 传</el-button>-->
      <!--        <el-button @click="cancelUpload">取 消</el-button>-->
      <!--      </div>-->
    </el-dialog>

    <el-dialog v-dialogDrag title="字段编辑" :visible.sync="outerVisible" width="55%">
      <el-table :data="fieldData" max-height="250">
        <el-table-column prop="columnName" label="字段名称"> </el-table-column>
        <el-table-column prop="columnCode" label="字段代码"> </el-table-column>
        <el-table-column prop="columnDescription" label="字段描述">
        </el-table-column>
        <el-table-column prop="dataType" label="字段数据类型">
        </el-table-column>
        <el-table-column prop="columnLength" label="字段长度" width="90">
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              @click.native.prevent="updateColumn(scope.$index, fieldData)"
              type="text"
              size="small"
            >
              修改
            </el-button>
            <el-button
              @click.native.prevent="deleteColumn(scope.$index, fieldData)"
              type="text"
              size="small"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-dialog
        width="50%"
        title="修改"
        :visible.sync="innerVisible"
        append-to-body
      >
        <el-form
          ref="innerForm"
          :label-position="labelPosition"
          label-width="80px"
          :model="innerForm"
          :rules="innerRules"
        >
          <el-form-item label="字段名称" prop="columnName">
            <span>{{innerForm.columnName}}</span>
          </el-form-item>
          <el-form-item label="字段代码" prop="columnCode">
            <el-input v-model="innerForm.columnCode"></el-input>
          </el-form-item>
          <el-form-item label="字段描述" prop="columnDescription">
            <el-input v-model="innerForm.columnDescription"></el-input>
          </el-form-item>
          <el-form-item label="数据类型" prop="dataType">
            <el-select
              v-model="innerForm.dataType"
              filterable
              placeholder="请选择数据类型"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="数据长度" prop="columnLength">
            <el-input v-model="innerForm.columnLength"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitInnerForm">提 交</el-button>
          <el-button @click="innerVisible = false">取 消</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="outerVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import upLoad from "./Upload";
import Cookies from "js-cookie";
import { getToken } from "@/utils/auth";
import {
  checkDataLength,
  checkTableExist,
  createTable,
  dataSave,
  delSdocColumn,
  getColumnListByDocId,
  getSdocColumn,
  listSdoc,
  updateSdocColumn,
} from "@/api/quota/sdoc/sdoc.js";

export default {
  name: "sdoc",
  components: { upLoad },
  data() {
    return {
      loading: false,
      options: [
        {
          value: "VARCHAR2",
          label: "varchar2",
        },
        {
          value: "CHAR",
          label: "char",
        },
        {
          value: "NUMBER",
          label: "number",
        },
        {
          value: "DATE",
          label: "date",
        },
      ],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      totalCount: 0,
      // Zone表格数据
      sdocList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openUploadFileDialog: false,
      outerVisible: false,
      innerVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: undefined,
        docName: undefined,
        docUrl: undefined,
        docTableCode: undefined,
        orderField: "UPDATE_DATE",
        order: "desc",
      },
      upload: {
        filePath: "filePath",
        headers: { Authorization: "Bearer " + getToken() },
        url: process.env.VUE_APP_BASE_API + "/filOpe/upload",
        updateSupport: 0,
      },
      labelPosition: "right",
      innerForm: {
        id: undefined,
        docId: undefined,
        columnName: "",
        columnCode: "",
        columnDescription: "",
        dataType: "",
        columnLength: 100,
      },
      innerRules: {
        columnName: [
          { required: true, message: "字段名不能为空", trigger: "blur" },
        ],
        columnCode: [
          { required: true, message: "字段代码不能为空", trigger: "blur" },
        ],
        columnDescription: [
          { required: true, message: "字段描述不能为空", trigger: "blur" },
        ],
        dataType: [
          { required: true, message: "数据类型不能为空", trigger: "blur" },
        ],
        columnLength: [
          { required: true, message: "数据长度不能为空", trigger: "blur" },
        ],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      fieldData: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    submitInnerForm() {
      console.log(this.innerForm);
      this.$refs["innerForm"].validate((valid) => {
        if (valid) {
          updateSdocColumn(this.innerForm).then((response) => {
            if (response.data === true) {
              this.msgSuccess("修改成功");
              this.innerVisible = false;
              this.getColumnListByDocId(this.innerForm.docId);
            }
          });
        }
      });
    },
    deleteColumn(index, rows) {
      const ids = rows[index].id;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delSdocColumn(ids);
        })
        .then((res) => {
          if (res.data) {
            this.msgSuccess(res.msg);
            this.getColumnListByDocId(rows[index].docId);
          } else {
            this.msgError(res.msg);
          }
        })
        .catch(function () {});
    },
    updateColumn(index, rows) {
      console.log("rows", rows);
      this.innerVisible = true;
      getSdocColumn(rows[index].id).then((res) => {
        this.innerForm = res.data;
      });
    },
    lookField(row) {
      this.getColumnListByDocId(row.id);
      this.outerVisible = true;
    },
    submitFileForm() {
      this.$refs.upload.submit();
    },
    cancelUpload() {
      this.openUploadFileDialog = false;
      this.$refs.upload.clearFiles();
    },
    //上传完成方法
    uploadSuccess(response, file, fileList) {
      if (response.code === 0) {
        this.msgSuccess("上传成功");
        this.getList();
      }
    },
    /** 查询文件管理数据 */
    getList() {
      this.loading = true;
      listSdoc(this.queryParams).then((response) => {
        this.sdocList = response.data.list;
        this.totalCount = response.data.totalCount;
        this.loading = false;
      });
    },
    getColumnListByDocId(docId) {
      getColumnListByDocId(docId).then((res) => {
        this.fieldData = res.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        zoneTitle: undefined,
        zoneDescription: undefined,
        createBy: Cookies.get("username"),
        createDate: undefined,
        updateBy: Cookies.get("username"),
        orderNum: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加主题域";
    },
    /** 创建表 */
    handleCreateTable(row) {
      let isExistTable = row.isExistTable;
      if (isExistTable === 1) {
        this.msgInfo("库表结构已存在!");
      } else {
        checkTableExist(row.docTableCode)
          .then((res) => {
            if (res.data === 1) {
              this.msgInfo("库表结构已存在!");
            } else {
              checkDataLength(row.id).then((res) => {
                let reason = res.data.reason;
                let status = res.data.status;
                if (status == 0 || status == 1) {
                  this.msgError(reason);
                } else {
                  createTable(row.id).then((res) => {
                    if (res.data === 1) {
                      this.msgSuccess("创建成功");
                      this.getList();
                    }
                  });
                }
              });
            }
          })
          .catch(() => {
            this.msgError("表结构已存在!");
          });
      }
    },
    handleDataSave(row) {
      this.loading = true;
      checkDataLength(row.id).then((res) => {
        this.loading = false;
        let reason = res.data.reason;
        let status = res.data.status;
        if (status == 0 || status == 1) {
          this.msgError(reason);
        } else {
          if (row.isExistTable == 0) {
            this.msgError("请先执行创建表操作");
          } else {
            dataSave(row.id)
              .then((res) => {
                this.loading = false;
                if (res.data) {
                  this.msgSuccess("导入完成");
                  this.getList();
                }
              })
              .catch(() => {
                this.loading = false;
                this.msgError("数据导入失败");
              });
          }
        }
      });
    },
    /** 提交按钮 */
    submitForm: function () {},
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delZone(ids);
        })
        .then((res) => {
          if (res.data === 0) {
            this.msgError("删除失败");
          } else {
            this.getList();
            this.msgSuccess("删除成功");
          }
        })
        .catch(function () {});
    },
  },
};
</script>
<style>
.class_upload {
  width: 500px;
  float: contour;
  margin-right: 500px;
  margin-left: 600px;
}

.uploadSlot {
  margin: -10px 10px 10px 30px;
}
</style>
